#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

/**
展示 线程同步
gcc -pthread --std=c99 thread_race.c
pthread_mutex_t
pthread_mutex_lock
pthread_mutex_unlock
*/
pthread_t tid1, tid2;
pthread_mutex_t my_lock = PTHREAD_MUTEX_INITIALIZER; // should be init
// or pthread_mutex_init(&mylock, NULL);
int count1;
int count2;


#define MAX 100000

// 2个线程同时执行，不做任何同步
void* add0() {
	for (int i = 0; i < MAX; i++) {
		count1++;
		count2++;
	}
	return (void*)0;
}

// 2个线程同时执行，代码中同步
void* add1() {
	pthread_mutex_lock(&my_lock);
	for (int i = 0; i < MAX; i++) {
		count1++;
		count2++;
	}
	pthread_mutex_unlock(&my_lock);
	return (void*)0;
}

// 2个线程同时执行，代码中部分同步
void* add2() {
	for (int i = 0; i < MAX; i++) count1++;
	pthread_mutex_lock(&my_lock);
	for (int i = 0; i < MAX; i++) count2++;
	pthread_mutex_unlock(&my_lock);
	return (void*)0;
}

void do_test(const char* s, void *(*thr_fun)(void*)) {
	count2 = 0;
	count1 = 0;
	pthread_create(&tid1, NULL, thr_fun, NULL);
	pthread_create(&tid2, NULL, thr_fun, NULL);
	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);
	printf("%s count1=%d,count2=%d\n", s, count1, count2);
}

int main(void) {
	do_test("sync  not:", add0);
	do_test("sync  all:", add1);
	do_test("sync part:", add2);
}
/*
you may run ./a.out multi times
sync  not: count1=174015,count2=174020
sync  all: count1=200000,count2=200000
sync part: count1=135245,count2=200000
*/